package com.ssd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssd.common.VMSystem;
import com.ssd.emq.utils.JWTUtil;
import com.ssd.entity.operation.dto.AssginRoleDto;
import com.ssd.entity.operation.dto.LoginDto;
import com.ssd.entity.operation.dto.SysUserDto;
import com.ssd.entity.operation.entity.SysRoleUser;
import com.ssd.entity.operation.entity.SysUser;
import com.ssd.entity.operation.vo.LoginVo;
import com.ssd.exception.LogicException;
import com.ssd.mapper.SysRoleUserMapper;
import com.ssd.mapper.SysUserMapper;
import com.ssd.service.SysRoleUserService;
import com.ssd.service.SysUserService;
import com.ssd.utils.JsonUtils;
import com.ssd.view.TokenObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private SysRoleUserService sysRoleUserService;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;
    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) throws IOException {

        //获取输入验证码和存储到redis的key名称  loginDto获取到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //2 根据获取的redis里面key ，查询redis里面存储验证码
        // set("user:validate"+key
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key).toString();

        //3 比较输入的验证码和 redis存储验证码是否一致
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)) {
            //4 如果不一致，提示用户，校验失败
            throw new LogicException("验证码错误");
        }

        //5 如果一致，删除redis里面验证码
        redisTemplate.delete("user:validate" + key);

        //1 获取提交用户名，loginDto获取到
        String userName = loginDto.getUserName();

        //2 根据用户名查询数据库表 sys_user表
        SysUser sysUser = lambdaQuery().eq(SysUser::getUserName,userName).one();

        //3 如果根据用户名查不到对应信息，用户不存在，返回错误信息
        if(sysUser == null) {
            throw new LogicException("用户名或者密码错误");
        }

        //4 如果根据用户名查询到用户信息，用户存在
        //5 获取输入的密码，比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        String input_password =
                DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //比较
        if(!input_password.equals(database_password)) {
            throw new LogicException("用户名或者密码错误");
        }

        //6 如果密码一致，登录成功，如果密码不一致登录失败
        //7 登录成功，生成用户唯一标识token
        //生成token
        TokenObject tokenObject = new TokenObject();
        // 设置用户ID
        tokenObject.setUserId(sysUser.getId());
        // 设置手机号，这里注释掉的代码是设置用户名，可能用于测试
        tokenObject.setMobile(sysUser.getPhone());
        //设置用户名称
        tokenObject.setUserName(sysUser.getUserName());
        //设置登录类型
        tokenObject.setLoginType(VMSystem.LOGIN_ADMIN);
        // 通过Token对象和密钥生成JWT
        String token = JWTUtil.createJWTByObj(tokenObject, VMSystem.JWT_SECRET);

        //9 返回loginvo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }






    //1 用户条件分页查询接口
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum,
                                        Integer pageSize,
                                        SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser>  pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //2 用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        //1 判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = lambdaQuery().eq(SysUser::getUserName,userName).one();
        if(dbSysUser != null) {
            throw new LogicException("用户名已经存在");
        }

        //2 输入密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        //设置status值  1 可用  0 不可用
        sysUser.setStatus(1);

        save(sysUser);
    }

    //3 用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        updateById(sysUser);
    }

    //4 用户删除
    @Override
    public void deleteById(Long userId) {
        removeById(userId);
    }


    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1 根据userId删除用户之前分配角色数据
        sysRoleUserService.lambdaUpdate().eq(SysRoleUser::getUserId,assginRoleDto.getUserId()).remove();

        //2 重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历得到每个角色id
        for(Long roleId:roleIdList) {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }

}
